package com.lagou.edu.factory;

import com.lagou.edu.annocation.Autowired;
import com.lagou.edu.annocation.Service;
import com.lagou.edu.annocation.Transactional;
import com.lagou.edu.utils.ClassUtil;
import com.lagou.edu.utils.StringUtils;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 应癫
 *
 * 工厂类，生产对象（使用反射技术）
 */

public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String,Object> map = new HashMap<>();  // 存储对象


/*    static {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element =  beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                System.out.println("id"+ id);
                // 存储到map中待用
                map.put(id,o);

            }

            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element =  propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if(method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject,map.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                map.put(parentId,parentObject);

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }*/


    static {
        try {
            //扫包
            List<Class<?>> classList = ClassUtil.getClassList(true, "com.lagou.edu");
            int i =0;
            for (Class<?> aClass : classList) {
                System.out.println(i++);
                if ( aClass.isAnnotationPresent(Service.class)){
                    String id =  aClass.getAnnotation(Service.class).value();
                    if ("".equals(id)) {
                        id = aClass.getName().replace(aClass.getPackageName()+".","");
                    }
                    // 通过反射技术实例化对象
                    Object o = aClass.newInstance();
                    map.put(StringUtils.toLowerCaseFirstOne(id), o);
                }

            }
            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            //存在@Autowired有依赖关系
            map.forEach((k,v)->{
                Field[] fields = v.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (field.isAnnotationPresent(Autowired.class)){
                        //需要处理依赖关系
                        String id =  field.getType().getName().replace( field.getType().getPackageName()+".","");
                        id = StringUtils.toLowerCaseFirstOne(id);
                        if (map.containsKey(id)){
                            field.setAccessible(true);
                            try {
                                field.set(v,  map.get(id));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }   else {
                            throw new RuntimeException("can not find "+ field.getType().getName());
                        }
                    }
                }

                //改用代理对象
                Class<?>[] interfaces = v.getClass().getInterfaces();
                if (interfaces != null && interfaces.length>0){
                    //jdk代理
                    Object jdkProxy = getJdkProxy(v);
                    // 存储到map中待用
                    map.put(k,jdkProxy);
                }   else {
                    //cglib代理
                    Object jdkProxy = getCglibProxy(v);
                    // 存储到map中待用
                    map.put(k,jdkProxy);
                }
            });

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }



    /**
     * Jdk动态代理
     * @param obj  委托对象
     * @return   代理对象
     */
    public static Object getJdkProxy(Object obj) {
        TransactionManager transactionManager = (TransactionManager) map.get("transactionManager");
        // 获取代理对象
        return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        //判断是否需要开启事务
                        boolean openTransactional = obj.getClass().isAnnotationPresent(Transactional.class) || obj.getClass().getMethod(method.getName(), method.getParameterTypes()).isAnnotationPresent(Transactional.class);

                        try{
                            if (openTransactional) {
                                transactionManager.beginTransaction();
                            }
                            result = method.invoke(obj,args);
                        }catch (Exception e) {
                            e.printStackTrace();
                            if (openTransactional) {
                                transactionManager.rollback();
                            }
                            // 抛出异常便于上层servlet捕获
                            throw e;

                        }
                        if (openTransactional) {
                            transactionManager.commit();
                        }
                        return result;
                    }
                });

    }


    /**
     * 使用cglib动态代理生成代理对象
     * @param obj 委托对象
     * @return
     */
    public static Object getCglibProxy(Object obj) {
        TransactionManager transactionManager = (TransactionManager) map.get("transactionManager");
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                boolean openTransactional = obj.getClass().isAnnotationPresent(Transactional.class) || obj.getClass().getMethod(method.getName(), method.getParameterTypes()).isAnnotationPresent(Transactional.class);
                try{
                    if (openTransactional) {
                        transactionManager.beginTransaction();
                    }
                    result = method.invoke(obj,objects);
                }catch (Exception e) {
                    e.printStackTrace();
                    if (openTransactional) {
                        transactionManager.rollback();
                    }
                    throw e;
                }
                if (openTransactional) {
                    transactionManager.commit();
                }
                return result;
            }
        });
    }



}
